﻿using process_monitor.Controller;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using Newtonsoft.Json;
using FluentFTP;
using System.Net;
using System.Web.UI.WebControls;

namespace process_monitor
{
    public partial class Form1 : Form
    {
        public static Form1 form;
        static string iniPath = Application.StartupPath.ToString() + @"\Config.ini";
        IniFiles ini = new IniFiles(iniPath);
        private string HOE_L = "\r\n             ";
        public Form1()
        {
            InitializeComponent();
            form = this; //相当于该窗体类的实例赋给了该静态变量form
            ini.FindAndCreate(iniPath);
            if (ini.IniReadValue("自助机", "主程序") == ""
                || ini.IniReadValue("自助机", "硬件") == "")
            {
                MessageBox.Show("请填写自助机配置后再打开程序");
                System.Environment.Exit(0);
            }
            MiniController.killProcess(@"cmd");
            MiniController.killProcess(@"electron");
            MiniController.killProcess(@"HisDHCom");
            MiniController.killProcess(@"kioskHDServer");
        }

        /// <summary>
        /// 日志开头时间
        /// </summary>
        /// <param name="log"></param>
        public void outPut(string log, int showSwitch = 1)
        {
            if (textBox1.GetLineFromCharIndex(textBox1.Text.Length) > 100)
                textBox1.Text = "";
            string outLog = DateTime.Now.ToString("HH:mm:ss     ") + log + "\r\n";
            if (showSwitch == 1)
            {
                textBox1.AppendText(outLog);
            }
            MiniController.WriteLog(outLog);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;   //是否允许多选
            dialog.Title = "请选择要处理的文件";  //窗口title
            dialog.Filter = "文本文件(*.exe)|*.*";   //可选择的文件类型
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox3.Text = dialog.FileName;  //获取文件路径
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;   //是否允许多选
            dialog.Title = "请选择要处理的文件";  //窗口title
            dialog.Filter = "文本文件(*.exe)|*.*";   //可选择的文件类型
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox4.Text = dialog.FileName;  //获取文件路径
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;   //是否允许多选
            dialog.Title = "请选择要处理的文件";  //窗口title
            dialog.Filter = "文本文件(*.exe)|*.*";   //可选择的文件类型
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox5.Text = dialog.FileName;  //获取文件路径
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                // 自助机主程序
                if (!MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox3.Text)))
                {
                    //MiniController.killProcess(@"cmd");
                    /*string folderPath = @"C:\Users\cc\AppData\Roaming\triageClient";
                    try
                    {
                        if (Directory.Exists(folderPath))
                        {
                            Directory.Delete(folderPath, true); // 第二个参数为true表示递归删除子文件夹和文件
                            outPut($"Folder {folderPath} 已删除.");
                        }
                        else
                        {
                            outPut($"Folder {folderPath} 不存在.");
                        }
                    }
                    catch (Exception ex)
                    {
                        outPut($"Error deleting folder {folderPath}: {ex.Message}");
                    }
                    */
                    // 等待2秒
                    outPut($"{textBox3.Text} 未运行，已重启。");
                    notifyIcon1.ShowBalloonTip(0, "重启完成", $"{textBox3.Text} 未运行，已重启。", ToolTipIcon.Info);
                    MiniController.StartProcess(@"D:\jandar\electron-v8.2.3-win32-x64\electron.bat");
                    Thread.Sleep(TimeSpan.FromSeconds(6));
                    outPut($"{textBox3.Text} 重启完成。");
                }
                // 自助机硬件
                if (!MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox4.Text)))
                {
                    outPut($"{textBox4.Text} 未运行，已重启。");
                    notifyIcon1.ShowBalloonTip(0, "重启完成", $"{textBox4.Text} 未运行，已重启。", ToolTipIcon.Info);
                    MiniController.killProcess(@"HisDHCom");
                    MiniController.StartProcess(textBox4.Text);
                }
                // 发票程序
                if (textBox5.Text != ""&& textBox5.Text != "null")
                {
                    if (!MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox5.Text)))
                    {
                        outPut($"{textBox5.Text} 未运行，已重启。");
                        MiniController.StartProcess(textBox5.Text);
                        notifyIcon1.ShowBalloonTip(0, "重启完成", $"{textBox5.Text} 未运行，已重启。", ToolTipIcon.Info);
                        MiniController.StartProcess(@"D:\Program Files (x86)\Bosssoft\Assistant\BosssoftAssistant.exe");
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            // 设置条件，如果条件成立则背景颜色为绿色，否则为红色
            bool condition1 = MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox3.Text)); // 你的条件，可以根据实际情况设置
            label5.ForeColor = condition1 ? Color.Green : Color.Red;
            // 设置条件，如果条件成立则背景颜色为绿色，否则为红色
            bool condition2 = MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox4.Text)); // 你的条件，可以根据实际情况设置
            label6.ForeColor = condition2 ? Color.Green : Color.Red;
            // 设置条件，如果条件成立则背景颜色为绿色，否则为红色
            if (textBox5.Text != "" && textBox5.Text != "null") {
                bool condition3 = MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox5.Text)); // 你的条件，可以根据实际情况设置
                label7.ForeColor = condition3 ? Color.Green : Color.Red;
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox3.Text = ini.IniReadValue("自助机", "主程序");
            textBox4.Text = ini.IniReadValue("自助机", "硬件");
            textBox5.Text = ini.IniReadValue("自助机", "发票");
            form.WindowState = FormWindowState.Minimized; // 将窗体最小化到任务栏

            checkBox1.Checked = false;
            // 更新程序
            // 从指定服务器获取JSON数据
            string jsonUrl = "http://192.168.0.128:9001";
            string jsonData = GetJsonData(jsonUrl);
            outPut(jsonData);
            mainUpdate(jsonData);
            fundUpdate(jsonData, "KioskHDServer", @"kioskHDServer");
            fundUpdate(jsonData, "electron-v8.2.3-win32-x64", @"cmd");
            checkBox1.Checked = true;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (MiniController.IsProcessRunning(Path.GetFileNameWithoutExtension(textBox5.Text)))
            {
                outPut($"{textBox5.Text} 重启中。");
                notifyIcon1.ShowBalloonTip(0, "重启中",  $"{textBox5.Text} 重启中。", ToolTipIcon.Info);
                MiniController.killProcess(@"BsService");
                MiniController.killProcess(Path.GetFileNameWithoutExtension(textBox5.Text));
                timer3.Enabled= false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 正常显示窗体
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
            // this.Show();
        }

        private void 显示自助机进程守护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 正常显示窗体
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
            // this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        public void mainUpdate(string jsonData)
        {
            outPut($"检测进程守护程序更新中");
            if (!string.IsNullOrEmpty(jsonData))
            {
                //outPut($"jsonData不为空");

                // 解析JSON数据
                //var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
                MyData data = JsonConvert.DeserializeObject<MyData>(jsonData);

                // 将数据存储在数组中
                List<string> dataArray = new List<string>
                {
                    data.KioskHDServer,
                    data.electron,
                    data.process
                };

                if (data.process != ini.IniReadValue("自助机", "process_monitor") && data.process != "")
                {
                    // 执行FTP文件传输操作
                    string ftpServer = "ftp://192.168.0.128";
                    string ftpUsername = "upjandar_128_com";
                    string ftpPassword = "cSmiAYb3bJJfjk8H";
                    string remoteDirectory = @"/process_monitor";
                    string localDirectory = @"D:\process_monitor\temp";
                    //outPut(remoteDirectory);
                    using (FtpClient ftpClient = new FtpClient(ftpServer, ftpUsername, ftpPassword))
                    {
                        ftpClient.Connect();
                        /*var files = ftpClient.GetListing();

                        foreach (FtpListItem item in files)
                        {
                            string remoteFile = item.FullName;
                            outPut($"{remoteFile}");
                        }*/

                        ftpClient.SetWorkingDirectory(remoteDirectory);
                        var files = ftpClient.GetListing();

                        foreach (FtpListItem item in files)
                        {
                            if (item.Type == FtpFileSystemObjectType.File)
                            {
                                string remoteFile = item.FullName;
                                string localFile = Path.Combine(localDirectory, item.Name);
                                ftpClient.DownloadFile(localFile, remoteFile, FtpLocalExists.Overwrite, FtpVerify.None);
                                outPut($"Downloaded: {remoteFile} to {localFile}");
                            }
                        }
                    }
                    ini.IniWriteValue("自助机", "process_monitor", data.process);
                    outPut($"更新进程守护程序完成，即将重启");
                    notifyIcon1.ShowBalloonTip(0, "重启中", $"更新进程守护程序完成，即将重启", ToolTipIcon.Info);
                    MiniController.StartProcess(@"D:\process_monitor\update_process_monitor.bat");
                }
            }
            else
            {
                outPut("Failed to retrieve JSON data.");
            }
        }

        /// <summary>
        /// 更新程序
        /// </summary>
        /// <param name="jsonData">json串</param>
        /// <param name="键名">ini键名</param>
        /// <param name="进程名称">更新前结束进程名称</param>
        public void fundUpdate(string jsonData, string 键名, string 进程名称)
        {
            outPut($"检测{键名}更新中");
            if (!string.IsNullOrEmpty(jsonData))
            {
                //outPut($"jsonData不为空");

                // 解析JSON数据
                //var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
                MyData data = JsonConvert.DeserializeObject<MyData>(jsonData);

                // 将数据存储在数组中
                List<string> dataArray = new List<string>
                {
                    data.KioskHDServer,
                    data.electron,
                    data.process
                };

                // 现在，dataArray 包含了 JSON 数据的数组表示
                /*foreach (string item in dataArray)
                {
                    Console.WriteLine(item);
                }*/
                string dataValue = "";
                if (键名 == "KioskHDServer")
                {
                    dataValue = data.KioskHDServer;
                }else if (键名 == "electron-v8.2.3-win32-x64")
                {
                    dataValue = data.electron;
                }
                //outPut(data.KioskHDServer + "|" + data.electron);
                // 检查KioskHDServer的值
                //outPut(dataValue + " " + ini.IniReadValue("自助机", 键名));
                if (dataValue != ini.IniReadValue("自助机", 键名) && dataValue != "")
                {
                    // 执行FTP文件传输操作
                    string ftpServer = "ftp://192.168.0.128";
                    string ftpUsername = "upjandar_128_com";
                    string ftpPassword = "cSmiAYb3bJJfjk8H";
                    string remoteDirectory = "/" + 键名;
                    string localDirectory = $@"D:\jandar\{键名}";
                    //outPut(remoteDirectory);
                    MiniController.killProcess(进程名称);
                    if (进程名称 == "KioskHDServer") MiniController.killProcess(@"HisDHCom");
                    if (进程名称 == "cmd") MiniController.killProcess(@"electron");
                    using (FtpClient ftpClient = new FtpClient(ftpServer, ftpUsername, ftpPassword))
                    {
                        ftpClient.Connect();
                        /*var files = ftpClient.GetListing();

                        foreach (FtpListItem item in files)
                        {
                            string remoteFile = item.FullName;
                            outPut($"{remoteFile}");
                        }*/
                        DownloadFolderAndFiles(ftpClient, remoteDirectory, localDirectory);
                        
                        /*ftpClient.SetWorkingDirectory(remoteDirectory);
                        var files = ftpClient.GetListing();

                        foreach (FtpListItem item in files)
                        {
                            if (item.Type == FtpFileSystemObjectType.File)
                            {
                                string remoteFile = item.FullName;
                                string localFile = Path.Combine(localDirectory, item.Name);
                                ftpClient.DownloadFile(localFile, remoteFile, FtpLocalExists.Overwrite, FtpVerify.None);
                                outPut($"Downloaded: {remoteFile} to {localFile}");
                            }
                            else if (item.Type == FtpFileSystemObjectType.Directory)
                            {
                                // 如果是文件夹，递归下载文件夹内的内容
                                string remoteSubDirectory = item.FullName;
                                string localSubDirectory = Path.Combine(localDirectory, item.Name);

                                if (!Directory.Exists(localSubDirectory))
                                {
                                    Directory.CreateDirectory(localSubDirectory);
                                }

                                //DownloadFolderAndFiles(ftpClient, remoteSubDirectory, localSubDirectory);
                            }
                        }*/
                    }
                    ini.IniWriteValue("自助机", 键名, dataValue);
                    outPut($"更新{键名}完成");
                    notifyIcon1.ShowBalloonTip(0, "更新完成", $"更新{键名}完成", ToolTipIcon.Info);
                }
            }
            else
            {
                outPut("Failed to retrieve JSON data.");
            }
        }

        public static void DownloadFolderAndFiles(FtpClient ftpClient, string remoteDirectory, string localDirectory)
        {
            // 获取远程目录的文件列表
            var files = ftpClient.GetListing(remoteDirectory);

            foreach (FtpListItem item in files)
            {
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    // 如果是文件，下载文件
                    string remoteFile = item.FullName;
                    string localFile = Path.Combine(localDirectory, item.Name);
                    ftpClient.DownloadFile(localFile, remoteFile, FtpLocalExists.Overwrite, FtpVerify.None);
                    form.outPut($"Downloaded: {remoteFile} to {localFile}");
                }
                else if (item.Type == FtpFileSystemObjectType.Directory)
                {
                    // 如果是文件夹，递归下载文件夹内的内容
                    string remoteSubDirectory = item.FullName;
                    string localSubDirectory = Path.Combine(localDirectory, item.Name);

                    if (!Directory.Exists(localSubDirectory))
                    {
                        Directory.CreateDirectory(localSubDirectory);
                        form.outPut($"Created: {localSubDirectory}");
                    }

                    DownloadFolderAndFiles(ftpClient, remoteSubDirectory, localSubDirectory);
                }
            }
        }

        public string GetJsonData(string url)
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    return client.DownloadString(url);
                }
            }
            catch (Exception ex)
            {
                outPut($"Error retrieving JSON data: {ex.Message}");
                return null;
            }
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            checkBox1.Checked = false;
            // 更新程序
            // 从指定服务器获取JSON数据
            string jsonUrl = "http://192.168.0.128:9001";
            string jsonData = GetJsonData(jsonUrl);
            outPut(jsonData);
            mainUpdate(jsonData);
            fundUpdate(jsonData, "KioskHDServer", @"kioskHDServer");
            fundUpdate(jsonData, "electron-v8.2.3-win32-x64", @"cmd");
            checkBox1.Checked = true;
        }
    }
    public class MyData
    {
        public string KioskHDServer { get; set; }
        public string electron { get; set; }
        public string process { get; set; }
    }
}
